<template>
	<picker style="width: 100%;height: 100%;display:flex;align-items:center;" mode="multiSelector" @columnchange="colChange" @change="change" :value="valueIndex" :range="rangeData" :range-key="name">{{text}}</picker>
</template>

<script>
	export default{
		name:'MultipleColPicker',
		data(){
			return{
				rangeData:[],
				valueIndex:[],
			}
		},
		props:{
			range:{
				type:Array,
				default:()=>[]
			},
			name:{
				type:String,
				default:'name',
			},
			child:{
				type:String,
				default:'child',
			},
			value:{
				type:Number,
				default:0
			}
		},
		computed:{
			text(){
				if(this.rangeData.length===0)return '';
				let text='';
				let current=this.range;
				this.rangeData.forEach((item,index)=>{
					text+=current[this.valueIndex[index]].name+'-';
					current=current[this.valueIndex[index]].child
				})
				text=text.substr(0,text.length-1)
				return text;
			}
		},
		watch:{
			range:{
				handler(val){
					if(val.length==0){
						return [];
					}
					this.valueIndex=[];
					this.rangeData=[];
					let data=[];
					let loop=true;
					let current=val;
					data.push(current);
					this.valueIndex.push(0)
					while(loop){
						if(current[0].child){
							this.valueIndex.push(0)
							data.push([...current[0].child])
							current=current[0].child;
						}else{
							loop=false;
							break;
						}
					}
					this.rangeData=data;
					if(this.value){
						this.initSelect(val);
					}
				},
				immediate:true
			},
			value:{
				handler(val){
					this.initSelect(this.range);
				},
				immediate:true
			}
		},
		methods:{
			colChange(e){
				let col=e.detail.column;
				let index=e.detail.value;
				if(col===this.rangeData.length-1)return;
				let current=this.rangeData[col][index].child;
				for(let i=0;i<this.rangeData.length-col-1;i++){
					this.$set(this.rangeData,i+1,current);
					current=current[0].child
				}
			},
			change(e){
				let value=e.detail.value;
				this.$emit('selected',this.rangeData[this.rangeData.length-1][value[value.length-1]].id)
			},
			initSelect(val){
				let index=this.mapData(val);
				if(index){
					this.valueIndex=index.reverse();
				}
			},
			mapData(data,level=0){
				for(let i=0;i<data.length;i++){
					let c=data[i];
					if(c.id==this.value){
						return [i];
					}
					if(c.child){
						let res=this.mapData(c.child,level+1)
						if(res){
							res.push(i)
							return res;
						}
					}
				}
			}
		}
	}
</script>

<style>
</style>